package cn.com.blueInfo.bpm.system.repository.impl;

import cn.com.blueInfo.bpm.common.enums.BaseDeleted;
import cn.com.blueInfo.bpm.common.enums.BaseStatus;
import cn.com.blueInfo.bpm.system.entity.Application;
import cn.com.blueInfo.bpm.system.mapper.ApplicationMapper;
import cn.com.blueInfo.bpm.system.repository.ApplicationRepository;
import cn.com.blueInfo.bpm.system.request.ApplicationDTO;
import cn.com.blueInfo.utils.error.BusinessException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 租户系统表 数据服务实现类
 * @author suxch
 * @since 2025-09-01 19:17:41
 */
@Log4j2
@Service
public class ApplicationRepositoryImpl
        extends ServiceImpl<ApplicationMapper, Application>
        implements ApplicationRepository {

    /**
     * 新增租户系统
     * @param application 租户系统参数
     */
    @Override
    public Integer createApplication(Application application) {
        return sqlExecuteResult(save(application));
    }

    /**
     * 批量新增租户系统
     * @param applicationList 租户系统参数列表
     */
    @Override
    public Integer batchCreateApplication(List<Application> applicationList) {
        return sqlExecuteResult(saveBatch(applicationList), applicationList.size());
    }

    /**
     * 删除租户系统
     * @param applicationId 租户系统ID
     */
    @Override
    public Integer deleteApplication(Long applicationId) {
        Application application = new Application();
        application.setId(applicationId);
        application.setDeleted(BaseDeleted.DELETED);
        return sqlExecuteResult(removeById(application));
    }

    /**
     * 批量删除租户系统
     * @param applicationIdList 租户系统ID列表
     */
    @Override
    public Integer batchDeleteApplication(List<Long> applicationIdList) {
        List<Application> applicationList = new ArrayList<>();
        for (Long applicationId : applicationIdList) {
            Application application = new Application();
            application.setId(applicationId);
            application.setDeleted(BaseDeleted.DELETED);
            applicationList.add(application);
        }
        return sqlExecuteResult(removeBatchByIds(applicationList), applicationList.size());
    }

    /**
     * 更新部分租户系统
     * @param application 租户系统参数
     */
    @Override
    public Integer updateApplicationPartial(Application application) {
        validateUpdateId(application.getId());
        LambdaUpdateWrapper<Application> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Application::getId, application.getId());
        return sqlExecuteResult(update(updateWrapper));
    }

    /**
     * 更新全部租户系统
     * @param application 租户系统参数
     */
    @Override
    public Integer updateApplication(Application application) {
        validateUpdateId(application.getId());
        return sqlExecuteResult(updateById(application));
    }

    /**
     * 查询一条租户系统
     * @param applicationId 租户系统ID
     */
    @Override
    public Application getApplicationById(Long applicationId) {
        LambdaQueryWrapper<Application> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Application::getId, applicationId);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询租户系统
     * @param applicationQueryDTO 租户系统参数
     */
    @Override
    public Page<Application> getApplicationPage(ApplicationDTO.QueryDTO applicationQueryDTO) {
        Page<Application> applicationPage = new Page<>(
                applicationQueryDTO.getPage(), applicationQueryDTO.getSize());
        LambdaQueryWrapper<Application> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, applicationQueryDTO);

        BaseDeleted deleted = applicationQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeletePage(applicationPage, queryWrapper);
        } else {
            return page(applicationPage, queryWrapper);
        }
    }

    /**
     * 根据条件查询 租户系统 数量
     * @param applicationQueryDTO 租户系统参数
     */
    @Override
    public Long getApplicationCount(ApplicationDTO.QueryDTO applicationQueryDTO) {
        LambdaQueryWrapper<Application> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, applicationQueryDTO);

        BaseDeleted deleted = applicationQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteCount(queryWrapper);
        } else {
            return count(queryWrapper);
        }
    }

    /**
     * 根据条件查询 租户系统
     * @param applicationQueryDTO 租户系统参数
     */
    @Override
    public List<Application> getApplicationList(ApplicationDTO.QueryDTO applicationQueryDTO) {
        LambdaQueryWrapper<Application> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, applicationQueryDTO);

        BaseDeleted deleted = applicationQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteList(queryWrapper);
        } else {
            return list(queryWrapper);
        }
    }

    private void queryWrapper(LambdaQueryWrapper<Application> queryWrapper,
                              ApplicationDTO.QueryDTO applicationQueryDto) {

        String appCode = applicationQueryDto.getAppCode();
        queryWrapper.eq(StringUtils.isNotBlank(appCode), Application::getAppCode, appCode);

        String appName = applicationQueryDto.getAppName();
        queryWrapper.eq(StringUtils.isNotBlank(appName), Application::getAppName, appName);

        String description = applicationQueryDto.getDescription();
        queryWrapper.eq(StringUtils.isNotBlank(description), Application::getDescription, description);

        addQueryWrapper(queryWrapper, applicationQueryDto);

    }

    /**
     * 添加公共查询条件
     * @param queryWrapper 字段值
     * @param queryDTO 查询内容
     */
    private void addQueryWrapper(LambdaQueryWrapper<Application> queryWrapper, ApplicationDTO.QueryDTO queryDTO) {

        Long tenantId = queryDTO.getTenantId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(tenantId), Application::getTenantId, tenantId);

        BaseDeleted deleted = queryDTO.getDeleted();
//        queryWrapper.eq(ObjectUtils.isEmpty(deleted), columnMap.get(BaseEntity.DELETED), BaseDeleted.NOT_DELETED);
        queryWrapper.eq(ObjectUtils.isNotEmpty(deleted), Application::getDeleted, deleted);

        BaseStatus status = queryDTO.getStatus();
//        queryWrapper.eq(ObjectUtils.isEmpty(status), columnMap.get(BaseEntity.STATUS), BaseStatus.ENABLED);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), Application::getStatus, status);

        Long createUserId = queryDTO.getCreateUserId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(createUserId), Application::getCreateUserId, createUserId);

        LocalDateTime startCreateTime = queryDTO.getStartCreateTime();
        LocalDateTime endCreateTime = queryDTO.getEndCreateTime();
        queryWrapper.between(ObjectUtils.isNotEmpty(startCreateTime) && ObjectUtils.isNotEmpty(endCreateTime),
                Application::getCreateTime, startCreateTime, endCreateTime);

        Long updateUserId = queryDTO.getUpdateUserId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(updateUserId), Application::getUpdateUserId, updateUserId);

        LocalDateTime startUpdateTime = queryDTO.getStartUpdateTime();
        LocalDateTime endUpdateTime = queryDTO.getEndUpdateTime();
        queryWrapper.between(ObjectUtils.isNotEmpty(startUpdateTime) && ObjectUtils.isNotEmpty(endUpdateTime),
                Application::getUpdateTime, startUpdateTime, endUpdateTime);

        Long deleteUserId = queryDTO.getDeleteUserId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(deleteUserId), Application::getDeleteUserId, deleteUserId);

        LocalDateTime startDeleteTime = queryDTO.getStartDeleteTime();
        LocalDateTime endDeleteTime = queryDTO.getEndDeleteTime();
        queryWrapper.between(ObjectUtils.isNotEmpty(startDeleteTime) && ObjectUtils.isNotEmpty(endDeleteTime),
                Application::getDeleteTime, startDeleteTime, endDeleteTime);

        Integer orderNumber = queryDTO.getOrderNumber();
        queryWrapper.eq(ObjectUtils.isNotEmpty(orderNumber), Application::getOrderNumber, orderNumber);

        String remark = queryDTO.getRemark();
        queryWrapper.eq(StringUtils.isNotBlank(remark), Application::getRemark, remark);

        String extend1 = queryDTO.getExtend1();
        queryWrapper.eq(StringUtils.isNotBlank(extend1), Application::getExtend1, extend1);

        String extend2 = queryDTO.getExtend2();
        queryWrapper.eq(StringUtils.isNotBlank(extend2), Application::getExtend2, extend2);

        JSONObject extend3 = queryDTO.getExtend3();
        queryWrapper.eq(ObjectUtils.isNotEmpty(extend3), Application::getExtend3, extend3);

    }

    /**
     * 验证更新ID是否存在
     * @param id 主键
     */
    private void validateUpdateId(Long id) {
        if (id == null || String.valueOf(id).length() < 10) {
            throw new BusinessException(500, "没有ID不能更新数据行！");
        }
    }

    /**
     * 返回数字类型的SQL执行结果
     * @param execute 执行结果
     * @return Integer
     */
    private Integer sqlExecuteResult(Boolean execute) {
        return execute ? 1 : 0;
    }

    /**
     * 返回数字类型的SQL执行结果
     * @param execute 执行结果
     * @param size 执行数量
     * @return Integer
     */
    private Integer sqlExecuteResult(Boolean execute, Integer size) {
        return execute ? size : 0;
    }

}
